import requests
from bs4 import BeautifulSoup


def read_html_file(file_path):
    """
    此函数用于读取本地 HTML 文件并提取文本内容
    :param file_path: HTML 文件的本地路径
    :return: 提取的文本内容
    """
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            html_content = file.read()
        soup = BeautifulSoup(html_content, 'html.parser')
        text = soup.get_text()
        return text
    except FileNotFoundError:
        print(f"错误：未找到文件 {file_path}")
        return None
    except Exception as e:
        print(f"读取文件时出现错误: {e}")
        return None


def call_ollama_api(prompt):
    """
    此函数用于调用 Ollama API 获取模型响应
    :param prompt: 发送给模型的提示信息
    :return: 模型的响应文本
    """
    url = 'http://localhost:11434/api/generate'
    headers = {'Content-Type': 'application/json'}
    data = {
        'model': 'reader-lm:1.5b',
        'prompt': prompt,
        'stream': False
    }
    try:
        response = requests.post(url, headers=headers, json=data)
        response.raise_for_status()
        result = response.json()
        return result.get('response', '')
    except requests.RequestException as e:
        print(f"请求 Ollama API 时出现错误: {e}")
        return None
    except ValueError:
        print("无法解析 Ollama API 的响应为 JSON 格式")
        return None


if __name__ == "__main__":
    html_file_path = r'.\resources\test.html'  # 替换为你的本地 HTML 文件路径
    html_text = read_html_file(html_file_path)
    if html_text:
        # 这里可以根据需求修改提示信息
        prompt = f"{html_text}"
        ollama_response = call_ollama_api(prompt)
        if ollama_response:
            print(ollama_response)
